package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.ProcessDiffPayRecord;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;

/**
 * Description:
 *
 * @author Yanxinhao on 2025/2/13
 */
@Component(value = "1002")
public class ProcessTrackTypePayRecord implements ProcessDiffPayRecord {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    /**
     * 处理消费类型是购买音频的
     * 且用户成功支付的后置操作
     * @param userPaidRecordVo 用户支付记录
     */
    @Override
    public void processPayRecord(UserPaidRecordVo userPaidRecordVo) {
        //保存数据到user_paid_track表中
        String orderNo = userPaidRecordVo.getOrderNo();

        //健壮性检查
        LambdaQueryWrapper<UserPaidTrack> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPaidTrack::getOrderNo,orderNo);
        UserPaidTrack userPaidTrack = userPaidTrackMapper.selectOne(wrapper);
        if (userPaidTrack != null){
            throw new GuiguException(201,"user_paid_track表中已存在相同数据");
        }

        //先通过itemIdList中的任意一个音频id,获取音频对象,在获取专辑id
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        Long trackIdFromRecord = itemIdList.get(0);
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfoById(trackIdFromRecord);
        TrackInfo trackInfo = trackInfoResult.getData();
        Assert.notNull(trackInfo,"[ProcessTrackTypePayRecord]中调用track微服务的[getTrackInfoById]方法失败");
        Long albumId = trackInfo.getAlbumId();

        //遍历itemIdList(即TrackIdList) 来向数据库插入购买的音频数据
        itemIdList.stream().forEach(trackId -> {
            UserPaidTrack userPaidTrack1 = new UserPaidTrack();
            userPaidTrack1.setOrderNo(orderNo);
            userPaidTrack1.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack1.setAlbumId(albumId);
            userPaidTrack1.setTrackId(trackId);

            userPaidTrackMapper.insert(userPaidTrack1);
        });
    }
}